<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/6
 * Time: 19:29
 */

namespace app\api\service;

use app\api\model\Book;
use app\api\model\Money;
use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;
use app\lib\enum\OrderStatusEnum;
use app\lib\enum\OrderTypeEnum;
use app\lib\Exception\OrderException;
use app\lib\Exception\VirtualPayException;
use think\Db;
use think\Exception;

class VirtualPay
{
    private $orderID;
    private $orderNO;
    private $uid;

    function __construct($orderID)
    {
        if(!$orderID){
            throw new Exception('订单号不能为空');
        }

        $order = OrderModel::get($orderID);
        $this->orderID = $orderID;
        $this->orderNO = $order->order_no;
        $this->uid = $order->user_id;
    }

    // 虚拟的pay BuyOrder
    public function payBuyOrder()
    {
        // 合法操作检查

        OrderService::checkOrderValid($this->orderID, OrderTypeEnum::Buy, OrderStatusEnum::UNPAID);



        // 库存
        $orderService = new OrderService();
        $orderState = $orderService->checkOrderState($this->orderID);


        // 还没付款  没库存了
        if (!$orderState['pass']) {
            throw new OrderException([
                'info' => '库存不足',
                'errorCode'=> 80005,
                'stateCode' => 400
            ]);
        }

        Db::startTrans();
        try {
            // 钱够吗
            $orderPrice = $orderState['orderPrice'];

            $money = Money::getCurrentMoney($this->uid);

            if ($money - $orderPrice < 0) {
                throw new VirtualPayException();
            }

            // 钱  库存 都够
            // 减钱
            $moneyModel = new Money();
            $moneyModel->user_id = $this->uid;
            $moneyModel->order_no = $this->orderNO;
            $moneyModel->operate = -1 * $orderPrice;
            $moneyModel->current_money = $money - $orderPrice;
            $moneyModel->save();

                // 减库存
            $this->DecStock($orderState['bookStatusArray']);
            // 改状态
            $this->changeStatus();

            Db::commit();
            return true;
        }
        catch(Exception $ex){
            Db::rollback();
            throw $ex;
        }
    }



    // 虚拟的pay RecycleOrder cms打款给用户
    public function payRecycleOrder()
    {
        // 合法操作检查
        OrderService::checkOrderValid($this->orderID, OrderTypeEnum::Recycle, OrderStatusEnum::DELIVERED);

        Db::startTrans();
        try {
            $orderService = new OrderService();
            $orderState = $orderService->checkOrderState($this->orderID);

            // 更新余额
            $orderPrice = $orderState['orderPrice'];

            $money = Money::getCurrentMoney($this->uid);
            $moneyModel = new Money();
            $moneyModel->user_id = $this->uid;
            $moneyModel->order_no = $this->orderNO;
            $moneyModel->operate = $orderPrice;
            $moneyModel->current_money = $money + $orderPrice;
            $moneyModel->save();

            // 更新订单状态
            $this->changeStatus();

            // 更新库存
            $this->AddStock($orderState['bookStatusArray']);

            Db::commit();
            return true;

        }catch (Exception $ex){
            Db::rollback();
            throw $ex;
        }
    }


    private function changeStatus(){
        OrderModel::where('id','=',$this->orderID)->update(['status' => OrderStatusEnum::PAID]);
    }

    private function DecStock( $bookArray){
        foreach ($bookArray as $book){
            Book::where('id','=',$book['id'])->setDec('stock', $book['count']);
        }
    }
    private function AddStock( $bookArray){
        foreach ($bookArray as $book){
            Book::where('id','=',$book['id'])->setInc('stock', $book['count']);
        }
    }

}